<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import resize from "./mixins/resize";

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "barChart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "100%",
    },
    barOptions: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  watch: {
    barOptions: {
      deep: true,
      handler(val) {
        this.setOptions(val);
      },
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = this.$echarts.init(this.$el);
      this.chart.setOption(this.barOptions, true);
    },
    setOptions({ title, labelLine, yAxis, xAxis, legend, series } = {}) {
      this.chart.setOption(
        {
          title: title,
          xAxis: xAxis,
          labelLine: labelLine,
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "shadow",
            },
          },
          grid: {
            top: 30,
            left: "2%",
            right: "2%",
            bottom: "10%",
            containLabel: true,
          },
          yAxis: yAxis,
          legend: legend,
          series: series,
        },
        true
      );
    },
  },
};
</script>
